导航菜单
首页 >  Question about extracting images from files with GPT4o  > How to load a local image to gpt4

How to load a local image to gpt4

import os

This code is for v1 of the openai package: openai · PyPIpip install openaipip install requests

from openai import OpenAIimport base64import requests

my_api_key = os.environ[“OPENAI_API_KEY”]

Function to encode the image

def encode_image(image_path):with open(image_path, “rb”) as image_file:return base64.b64encode(image_file.read()).decode(‘utf-8’)

Path to your image

image_path = “.\SourceImages\some_text.jpg”

Getting the base64 string

base64_image = encode_image(image_path)

Loads a local image file and OCRs it.https://platform.openai.com/docs/guides/vision

headers = {“Content-Type”: “application/json”,“Authorization”: f"Bearer {my_api_key}"}

payload = {“model”: “gpt-4-vision-preview”,“messages”: [{“role”: “user”,“content”: [{“type”: “text”,“text”: “What’s in this image?”},{“type”: “image_url”,“image_url”: {“url”: f"data:image/jpeg;base64,{base64_image}"}}]}],“max_tokens”: 300}

try:

response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)print(response.json())

except Exception as ex:print(“Exception:”, ex)

相关推荐: